import { State } from "framework/FSM/AState";
import { ActionArgHelper } from "../../../ActionManager/ActionArgHelper";
import { EntityHelper } from "utils/entity/EntityHelper";
import { PositionHelper } from "utils/position/PositionHelper";
 

/**
 * 行为模式
 * 采集行为
 * 升级行为
 */ 
export class HelpUpgradeTask<T extends IStateArg<Creep>>  extends State<T>
{
    //
    public  getActions(arg:T):Action[]
    {
        const memory = arg.entity.getNodeMemory();
        if(!memory.taskid)
        {
            return [];
        }
        const task =arg.task as ITask<ICreepTaskData<"helpBuild">>;
        if(!task)
        {
            // 查找不到任务
            return []
        }
        if(!task.data.room)
        {
            arg.entity.log(`error`,`${task.data.room}`,`任务错误 room参数不存在`)
        } 
        const creep = arg.entity;  
        {
            // 在自己家先带好能量
            if(creep.room.name == creep.ownerRoom().name && creep.store.getFreeCapacity()>0)
            {
                const store = creep.getEntity("CoreEntity").getTakeStores({resourceType:RESOURCE_ENERGY,amount:creep.store.getFreeCapacity()});
                if(store.length)
                {
                    return [ActionArgHelper.actionWithdraw(creep,store[0])]
                }
            }
        }
      
        if(creep.room.name!= task.data.room  || PositionHelper.isInExit(creep.pos))
        {
            return [ActionArgHelper.actionMoveto(creep,{pos:PositionHelper.roomCenter(task.data.room),range:10,}, {IsEludeHostile:true,IsRealtime:true,portal:task.data.portal})]
        }
     
        const work_room = Game.rooms[task.data.room as string] as Required<Room>;
        if(!work_room || work_room.getType() !=1) 
        {
            arg.entity.log(`error`,`${task.data.room}`,`升级房间不是我得房间 [${JSON.stringify(task)}]`)
            return []
        }
        // 建造任务
        // 1.能量不足。则取取能量
        // 1.a sourceid 存在。且能量足够 => withdraw
        // 1.b !(sourceid 存在。且能量足够) => 更新sourceId

        if(creep.store.getUsedCapacity(RESOURCE_ENERGY)==0)
        {
            creep.memory.state = 0;

        }
        else  if(creep.store.getFreeCapacity(RESOURCE_ENERGY)==0)
        {
            creep.memory.state = 1;
        }
        if(creep.memory.state)
        {
            if(work_room.controller)
            {
                if(work_room.controller.level>=2)
                {
                    const poss = work_room.controller.pos.getFreeSpace(1);
               
                    const rams = _.flatten(poss.map(e=>PositionHelper.lookFor(LOOK_STRUCTURES,e).filter(s=>s.structureType == STRUCTURE_RAMPART )));
                    if(rams.length == poss.length)
                    {
                        
                        // 
                        const r = rams.filter(e=>(e as any as StructureRampart).hits<20000)
                        if(r.length)
                        {
                            return [ActionArgHelper.actionRepair(creep,r[0] as any)]
                        }
                    }
                    else 
                    {
                        // 
    
                        const sites = _.flatten(poss.map(e=>e.lookFor(LOOK_CONSTRUCTION_SITES).filter(s=>s.structureType == STRUCTURE_RAMPART )));
                        if(sites.length>0)
                        {
                           
                            return [ActionArgHelper.actionBuild(creep,sites[0])]
                        }
                        else 
                        {
                            poss.forEach(e=>e.createConstructionSite(STRUCTURE_RAMPART));
                            
                        }
                    }
                    if(rams.filter(e=>!e.pos.lookMyCreep()))
                    {
                        return [ActionArgHelper.actionUpgrade(creep,work_room.controller as StructureController,1),]
                    }
                    else 
                    {
                        return [ActionArgHelper.actionUpgrade(creep,work_room.controller as StructureController,3),]
                    }
                }   
                else 
                {
                    return [ActionArgHelper.actionUpgrade(creep,work_room.controller as StructureController,3),]
                }    
                     
                
            }
            
        }
        else
        {
              // 取资源
            if(!creep.memory.sourceId)
            {
                // 设置取资源的移动目标
                {
                    const stores:AnyStoreStructure[]=[work_room.storage,work_room.terminal].concat(work_room.getStructures(STRUCTURE_CONTAINER) as any[]);
                
                    for(const e of stores)
                    {
                        if(e && e.store.getUsedCapacity(RESOURCE_ENERGY)>200)
                        {
                            creep.memory.sourceId = e.id;
                            break;
                        }
                    }
                }
                // 设置拾取资源的移动目标
                {
                    const res = _.sortBy(work_room.getResource(RESOURCE_ENERGY),e=>e.pos.distance(creep.pos));
                    for(const e of res)
                    {
                        if(e.amount>50)
                        {
                            creep.memory.sourceId = e.id;
                            break;
                        }
                    }
                }
                // 设置采集资源的移动目标
                {
                    const harvst = _.sortBy(work_room.getSource(),e=>e.pos.distance(creep.pos)).filter(e=>e.energy);
                    if(harvst.length>0)
                    {
                        creep.memory.sourceId =harvst[Math.round(Math.random()*Game.time)%harvst.length].id;
                    }
                    
                }
            }
            if(creep.memory.sourceId)
            {
                const store =  Game.getObjectById(creep.memory.sourceId as Id<AnyStoreStructure|Resource|Source>) ;
                if(store)
                {
                    if(creep.pos.distance(store.pos)>1)
                    {
                        return [ActionArgHelper.actionMoveto(creep,{pos:store.pos,range:1},{})]
                    }
                    if((store as Structure).structureType)
                    {
                        // 建筑
                        if((store as AnyStoreStructure).store.getUsedCapacity(RESOURCE_ENERGY)<10)
                        {
                            creep.memory.sourceId=undefined;
                        }
                        else 
                        {
                           
                            return [ActionArgHelper.actionWithdraw(creep,store as AnyStoreStructure,[{resourceType:RESOURCE_ENERGY}])]
                        }
                    }
                    else if((store as Resource).amount)
                    {
                       
                        return [ActionArgHelper.actionPickup(creep, (store as Resource))]
                        // resource
                    }else if((store as Source).energy)
                    {
                        // Source
                        return [ActionArgHelper.actionHarvest(creep, (store as Source))]
                    }else 
                    {
                        creep.memory.sourceId=undefined;
                    }
                }
                else 
                {
                    creep.memory.sourceId=undefined;
                }
            }
            
        }
        // 能量足够。则进行工作
        /**
         * targetId 不存在 -> targetId
         * targetId  存在 -> 进行工作
        */
        creep.log("warn","移动援助升级 未知行为")
        return [ ];
    }
}
